class Category < ActiveRecord::Base    
  has_and_belongs_to_many :artworks
  has_and_belongs_to_many :published_artworks, :class_name => 'Artwork', :conditions => {:published => true}
  has_many :category_descriptions
  has_many :category_names
  
  belongs_to :parent, 
             :class_name => 'Category', 
             :foreign_key => 'parent_id'
  
  #validates_presence_of :name
  
  acts_as_tree# :order=> "name"
  #acts_as_ferret :fields => [:name]
  
  def old_name
    begin
      read_attribute('name')
    rescue
      "<Error>"
    end
  end
  
  def path 
    cat_path = ""  
    for parent in self.ancestors.reverse
      cat_path += parent.name + " > " 
    end  
    return cat_path
  end
  
  def name_with_path
    return path + self.name
  end
  
  def to_param
    id.to_s + '-' + CGI.escape(name.downcase.gsub(' ', '-'))
  end
  
  def self.full_list(page)
    paginate :per_page => 10, :page => page, :order => 'id'
  end
  
  def name(language='English')
    begin
      ret = category_names.find(:first, :conditions => {:language => language})
      if ret.nil?
        ret = category_names.find(:first, :conditions => {:language => 'English'})
      end
    
      return ret.name
    rescue
      old_name
    end
  end
end
